#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#该备份脚本采用的是xtrabackup进行备份
import os
import sys
import time
import logging
import datetime
import subprocess

logging.basicConfig(level=logging.DEBUG,
                format='[%(asctime)s]  [%(levelname)s] %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                filename='/opt/dbbackup/mysql/logs/backupMysql.log',
                filemode='a')

DB_HOST = '10.0.14.214'
DB_USER = 'root'
DB_USER_PASSWD = 'root'
DataSave = 7
BACKUP_PATH = '/opt/dbbackup/mysql/'
DATETIME = time.strftime('%Y%m%d')
TODAYBACKUPPATH = BACKUP_PATH + DATETIME

#备份前检查，如果目录存在则退出，否则创建备份目录
def Check():
	if os.path.exists(TODAYBACKUPPATH):
		res = 'The backup directory already exists: %s. exit ...' % TODAYBACKUPPATH
		print(res)
		logging.error(res)
		sys.exit()
	else:
		os.makedirs(TODAYBACKUPPATH)
		res1 = "creating backup folder %s " % TODAYBACKUPPATH
		logging.info(res1)

#备份数据库
def Backup():
	Check()
	logging.info('Start backing up the database.')
	iArgs = "--slave-info  --no-timestamp"
	BackupCmd = "/usr/bin/innobackupex %s --host=%s  --user=%s --password=%s %s " %  (iArgs, DB_HOST, DB_USER, DB_USER_PASSWD, TODAYBACKUPPATH)
	p = subprocess.Popen(BackupCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
	stdout,stderr = p.communicate()
	logging.info(stdout)
	logging.info(stderr)
	logging.info('The database backup is complete')

#返回需要删除的时间点
def GetTimePoint(days):
	CurrTime = time.time()
	DelTime = 3600*24*int(days)
	TimePoint = CurrTime - DelTime
	return TimePoint

#删除文件夹的函数
def CheckDir(cdir):
	try:
		if os.path.isdir(cdir):
			os.rmdir(cdir)
			s = 'remove dir %s succ ...' % cdir
			logging.info(s)
	except Exception as e:
		s = 'remove dir %s FAIL !!! %s' % (cdir,e)
		logging.error(s)

#遍历备份目录，获取目录mtime时间,比对时间戳，删除之前目录
def CleanOld(beforeTime, path):
	logging.warning('Start cleaning up old backup data...')
	for eachdir in os.listdir(path):
		f = path + eachdir
		lastMtime = os.stat(f).st_mtime
		if lastMtime <= beforeTime:
			CheckDir(f) 

if __name__ == '__main__':
	Backup()
	t = GetTimePoint(DataSave)
	CleanOld(t, BACKUP_PATH)

